﻿
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Services.BASE;
using XiangziProjectTemplete.Core.IRepository.Base;
using XiangziProjectTemplete.Core.Model;
using System.Threading.Tasks;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.IRepository.UnitOfWork;
using XiangziProjectTemplete.Core.Model.Views;
using System;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete;
using System.Linq;
using System.Collections.Generic;

namespace XiangziProjectTemplete.Core.Services
{
    /// <summary> 
    /// 表的中文注解服务接口实现 
    /// </summary>	 
    public class Les_StockInfoServices : BaseServices<Les_StockInfo>, ILes_StockInfoServices
    {
        private readonly IBaseRepository<Base_Material> _dal_Base_Material;
        private readonly IBaseRepository<Les_Mater_V_Station> _dal_Les_Mater_V_Station;
        private readonly IBaseRepository<Les_StockInfo> _dal;
        private readonly IBaseRepository<Base_Station> _dal_station;
        private readonly IBaseRepository<V_LES_BufferStockCollect> _dal_V_LES_BufferStockCollect;



        public Les_StockInfoServices(
            IBaseRepository<Base_Material> dal_Base_Material,
            IBaseRepository<Les_Mater_V_Station> dal_Les_Mater_V_Station,
            IBaseRepository<Base_Station> dal_station,
            IBaseRepository<V_LES_BufferStockCollect> dal_V_LES_BufferStockCollect, IBaseRepository<Les_StockInfo> dal)
        {
            this._dal_Base_Material = dal_Base_Material;
            this._dal_Les_Mater_V_Station = dal_Les_Mater_V_Station;
            this._dal_station = dal_station;
            this._dal_V_LES_BufferStockCollect = dal_V_LES_BufferStockCollect;
            this._dal = dal;
            base.BaseDal = dal;
        }



        /// <summary>
        /// 根据站点ID删除库存
        /// </summary>
        /// <param name="_les_PersonHandlerRecordServices"></param>
        /// <param name="staionId">站点ID</param>
        /// <param name="manualHandlerRemark"></param>
        /// <param name="_unitOfWork"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> DeleteStockByStationId(
            ILes_AgvTaskServices _les_AgvTaskServices,
            ILes_PersonHandlerRecordServices _les_PersonHandlerRecordServices,
            int staionId, string manualHandlerRemark, IUnitOfWork _unitOfWork, IUser _user, ILes_InOutStockRecordServices les_InOutStockRecordServices)
        {
            try
            {
                _unitOfWork.BeginTran();//开启事务

                List<Les_Mater_V_Station> updateMVSList = null;
                //Les_Mater_V_Station updateMVS = null;
                List<Base_Material> materialList = new List<Base_Material>();

                var stations = await _dal_station.Query(x => x.Id == staionId);
                var mvs = await _dal_Les_Mater_V_Station.Query(x => x.StationId == staionId);
                if (mvs != null && mvs.Count > 0)
                {
                    updateMVSList = mvs;
                    foreach (var item in mvs)
                    {
                        var materials = await _dal_Base_Material.Query(x => x.Id == item.MaterialId);
                        if (materials != null && materials.Count > 0)
                        {
                            materialList.AddRange(materials);
                        }
                    }
                }
                else
                {

                }
                var updateStation = stations[0];

                //验证站点是否被AGV任务占用
                var validateResult = await _les_AgvTaskServices.ValidateIsUsingAgvTaskForStation(updateStation);
                if (validateResult.success == false)
                {
                    return validateResult;
                }

                //更新站点
                updateStation.IsLock = 0;
                updateStation.IsFull = 0;
                updateStation.OperationRemark = "人工删除库存";
                updateStation.ModifyBy = _user.Name;
                updateStation.ModifyTime = DateTime.Now;

                await _dal_station.Update(updateStation);//提交修改数据

                await les_InOutStockRecordServices.SaveInOutStockRecord(_user,
                         Model.Enums.XiangziProjectTemplete.LESPublicCommon.InOutStockTypeEnum.出库, "清空库存", updateStation);

                //删除mvs
                if (updateMVSList != null && updateMVSList.Count > 0)
                {
                    foreach (var item in updateMVSList)
                    {
                        await _dal_Les_Mater_V_Station.Delete(item);
                    }
                }
                //删除物料
                string removeMaterialName = "";
                string removeBurdenWorkNo = "";
                if (materialList != null && materialList.Count > 0)
                {
                    foreach (var item in materialList)
                    {
                        removeMaterialName = item.MaterialName;
                        removeBurdenWorkNo = item.BurdenWorkNo;
                        await _dal_Base_Material.Delete(item);
                    }
                }

                //保存人工处理日志
                var _note = "清空站点[" + updateStation.StationCode + "," + updateStation.StationName + "]的库存!";
                await _les_PersonHandlerRecordServices.SavePersonHandlerRecord(_user, "清空站点库存",
                   manualHandlerRemark, _note, removeMaterialName, removeBurdenWorkNo, updateStation);


                _unitOfWork.CommitTran();
            }
            catch (System.Exception)
            {
                _unitOfWork.RollbackTran();
                throw;
            }

            return MessageModel<bool>.Success("成功");
        }

        /// <summary>
        /// 清空 某个区域的托盘或余料库存
        /// </summary>
        /// <param name="_unitOfWork"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> DeleteAllSalverStation(StoreAreaEnum storeAreaEnum,
            string remark,
            IUnitOfWork _unitOfWork, IUser _user
            , ILes_PersonHandlerRecordServices _les_PersonHandlerRecordServices, ILes_InOutStockRecordServices les_InOutStockRecordServices)
        {
            try
            {
                _unitOfWork.BeginTran();//开启事务

                //寻找所有的空托盘和余料的点位
                string str_storeAreaEnum = Convert.ToString(storeAreaEnum);
                var stockList = await _dal_V_LES_BufferStockCollect.Query(x =>
                  x.StoreAreaCode == str_storeAreaEnum
                   && (
                   x.PlaceTypeCode == Convert.ToInt32(StationPlaceTypeEnum.余料工位).ToString() ||
                    x.PlaceTypeCode == Convert.ToInt32(StationPlaceTypeEnum.托盘工位).ToString()
                   ));
                if (stockList != null && stockList.Count > 0)
                {
                    List<int> stationIdList = stockList.Select(x => x.StationId).ToList();
                    List<string> mvsList = stockList.Select(x => x.MVSId).ToList();
                    List<string> materList = stockList.Select(x => x.Id).ToList();

                    var stations = await _dal_station.Query(x => stationIdList.Contains(x.Id));
                    var mvs = await _dal_Les_Mater_V_Station.Query(x => mvsList.Contains(x.Id));
                    var materials = await _dal_Base_Material.Query(x => materList.Contains(x.Id));

                    //保存数据库
                    foreach (var sta in stations)
                    {
                        sta.IsFull = 0;
                        sta.OperationRemark = "清空库存";
                        await _dal_station.Update(sta);

                        await les_InOutStockRecordServices.SaveInOutStockRecord(_user,
                            Model.Enums.XiangziProjectTemplete.LESPublicCommon.InOutStockTypeEnum.出库, "清空库存", sta);
                    }
                    foreach (var item in mvs)
                    {
                        await _dal_Les_Mater_V_Station.DeleteById(item.Id);
                    }
                    foreach (var mater in materials)
                    {
                        await _dal_Base_Material.DeleteById(mater.Id);
                    }


                    //记录人工处理日志
                    var _note = remark;
                    await _les_PersonHandlerRecordServices.SavePersonHandlerRecord(_user, remark,
                       _note, _note, "", "");
                }

                _unitOfWork.CommitTran();
            }
            catch (System.Exception)
            {
                _unitOfWork.RollbackTran();
                throw;
            }

            return MessageModel<bool>.Success("成功");
        }


        /// <summary>
        /// 清空 某个区域的全部库存
        /// </summary>
        /// <param name="_unitOfWork"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> ClearStockByArea(StoreAreaEnum storeAreaEnum,
            string remark,
            IUnitOfWork _unitOfWork, IUser _user
            , ILes_PersonHandlerRecordServices _les_PersonHandlerRecordServices, ILes_InOutStockRecordServices les_InOutStockRecordServices)
        {
            try
            {
                _unitOfWork.BeginTran();//开启事务

                //寻找所有的点位
                string str_storeAreaEnum = Convert.ToString(storeAreaEnum);
                var stockList = await _dal_V_LES_BufferStockCollect.Query(x =>
                  x.StoreAreaCode == str_storeAreaEnum
                 );
                if (stockList != null && stockList.Count > 0)
                {
                    List<int> stationIdList = stockList.Select(x => x.StationId).ToList();
                    List<string> mvsList = stockList.Select(x => x.MVSId).ToList();
                    List<string> materList = stockList.Select(x => x.Id).ToList();

                    var stations = await _dal_station.Query(x => stationIdList.Contains(x.Id));
                    var mvs = await _dal_Les_Mater_V_Station.Query(x => mvsList.Contains(x.Id));
                    var materials = await _dal_Base_Material.Query(x => materList.Contains(x.Id));

                    //保存数据库
                    foreach (var sta in stations)
                    {
                        sta.IsFull = 0;
                        sta.OperationRemark = "清空库存";
                        await _dal_station.Update(sta);

                        await les_InOutStockRecordServices.SaveInOutStockRecord(_user,
                            Model.Enums.XiangziProjectTemplete.LESPublicCommon.InOutStockTypeEnum.出库, "清空库存", sta);
                    }
                    foreach (var item in mvs)
                    {
                        await _dal_Les_Mater_V_Station.DeleteById(item.Id);
                    }
                    foreach (var mater in materials)
                    {
                        await _dal_Base_Material.DeleteById(mater.Id);
                    }


                    //记录人工处理日志
                    var _note = remark;
                    await _les_PersonHandlerRecordServices.SavePersonHandlerRecord(_user, remark,
                       _note, _note, "", "");
                }

                _unitOfWork.CommitTran();
            }
            catch (System.Exception)
            {
                _unitOfWork.RollbackTran();
                throw;
            }

            return MessageModel<bool>.Success("成功");
        }
    }
}
